const assert = require('assert');

// 本质就是实现根节点到叶子结点的一个二维数组的排序
const list2tree = (list) => {
    let obj = {} // key: parent, value: value
    let tree = {}
    for(let i =0; i< list.length; i++){
        obj[list[i].parent] = list[i].value
    }

    const rec = (obj, key, tree) => {
        tree.value = obj[key]
        if(obj[key] in obj){
            tree.child = {}
            rec(obj, obj[key], tree.child)
        }
        
    }

    rec(obj, null, tree)
    return tree
}


const res = list2tree([
    {value: 1, parent: null},
    {value: 2, parent: 1},
    {value: 3, parent: 2}
])
assert.deepStrictEqual(res, {
    value: 1,
    child: {
        value: 2,
        child: {
            value: 3
        }
    }
})

const res2 = list2tree([{
    value: 2, parent: 1
}, {
    value: 4, parent: 3
}, {
    value: 1, parent: null,
}, {
    value: 3, parent: 2
}])

assert.deepStrictEqual(res2, {
    value: 1,
    child: {
        value: 2,
        child: {
            value: 3,
            child: {
                value: 4
            }
        }
    }
})
